// src/main/java/com/example/qqviewspringboot/controller/DynamicController.java

package com.example.qqviewspringboot.controller;

import com.example.qqviewspringboot.data.Dynamic;
import com.example.qqviewspringboot.data.DynamicImage;
import com.example.qqviewspringboot.data.User;
import com.example.qqviewspringboot.dto.DynamicCreateDTO;
import com.example.qqviewspringboot.dto.DynamicDTO;
import com.example.qqviewspringboot.service.DynamicService;
import com.example.qqviewspringboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/dynamics")
public class DynamicController {

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private UserRepository userRepository;

    /**
     * 发布动态
     * @param dynamicCreateDTO 发布动态的 DTO
     * @return 返回保存的动态对象
     */
    @PostMapping("/publish")
    public ResponseEntity<?> publishDynamic(@RequestBody DynamicCreateDTO dynamicCreateDTO) {
        if (dynamicCreateDTO == null || dynamicCreateDTO.getUserId() == null) {
            return ResponseEntity.badRequest().body("Invalid dynamic data");
        }

        // 创建 Dynamic 实体
        Dynamic dynamic = new Dynamic();
        dynamic.setUserId(dynamicCreateDTO.getUserId());
        dynamic.setContent(dynamicCreateDTO.getContent());
        // createdAt 会自动设置

        // 创建 DynamicImage 实体
        if (dynamicCreateDTO.getImageUris() != null && !dynamicCreateDTO.getImageUris().isEmpty()) {
            List<DynamicImage> images = dynamicCreateDTO.getImageUris().stream().map(uri -> {
                DynamicImage image = new DynamicImage();
                image.setImageUri(uri);
                image.setDynamic(dynamic); // 设置关联关系
                return image;
            }).collect(Collectors.toList());
            dynamic.setImages(images);
        }

        // 保存动态及其图片
        Dynamic savedDynamic = dynamicService.publishDynamic(dynamic);

        if (savedDynamic == null) {
            return ResponseEntity.status(500).body("Failed to save dynamic");
        }

        // 获取发布者信息
        User user = userRepository.findById(savedDynamic.getUserId()).orElse(null);
        String publisherName = (user != null) ? user.getName() : "Unknown";
        String avatarUri = (user != null) ? user.getAvatarUri() : null;

        // 构造 DynamicDTO
        DynamicDTO dynamicDTO = new DynamicDTO(
                savedDynamic.getId(),
                savedDynamic.getUserId(),
                savedDynamic.getContent(),
                savedDynamic.getCreatedAt() != null ? savedDynamic.getCreatedAt().toString() : null,
                savedDynamic.getImages() != null ? savedDynamic.getImages().stream().map(DynamicImage::getImageUri).collect(Collectors.toList()) : null,
                avatarUri,
                publisherName
        );

        return ResponseEntity.ok(dynamicDTO);
    }

    /**
     * 获取动态列表，可以通过 userId 过滤
     * @param userId 可选的用户ID，用于过滤动态
     * @return 返回动态列表
     */
    @GetMapping
    public ResponseEntity<List<DynamicDTO>> getDynamics(@RequestParam(required = false) Long userId) {
        List<Dynamic> dynamics;
        if (userId != null) {
            dynamics = dynamicService.getDynamicsByUserId(userId);
        } else {
            dynamics = dynamicService.getAllDynamics();
        }

        // Map Dynamics to DynamicDTOs
        List<DynamicDTO> dynamicDTOs = dynamics.stream().map(dynamic -> {
            // Fetch user info
            User user = userRepository.findById(dynamic.getUserId()).orElse(null);
            String avatarUri = (user != null) ? user.getAvatarUri() : null;
            String publisherName = (user != null) ? user.getName() : "Unknown"; // 获取发布者姓名

            // Get images URIs
            List<String> imageUris = dynamic.getImages().stream()
                    .map(DynamicImage::getImageUri)
                    .collect(Collectors.toList());

            // Format createdAt as String
            String createdAt = dynamic.getCreatedAt() != null ? dynamic.getCreatedAt().toString() : null;

            return new DynamicDTO(
                    dynamic.getId(),
                    dynamic.getUserId(),
                    dynamic.getContent(),
                    createdAt,
                    imageUris,
                    avatarUri,
                    publisherName // 设置发布者姓名
            );
        }).collect(Collectors.toList());

        return ResponseEntity.ok(dynamicDTOs);
    }
}
